<template>
    <div class="timestamp-tool">
        <div class="tool-header">
            <h1>时间戳批量转换</h1>
            <p>批量将 Unix 时间戳与日期字符串相互转换，支持多种格式与时区设置</p>
        </div>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>输入</span>
                            <div class="actions">
                                <el-button text size="small" @click="paste">粘贴</el-button>
                                <el-button text size="small" @click="clearInput">清空</el-button>
                            </div>
                        </div>
                    </template>

                    <el-input v-model="input" type="textarea" :rows="12" placeholder="可一次输入多个时间戳（单位秒/毫秒）或日期，如：
1700821800
2025-11-25 14:30:00
Tue, 25 Nov 2025 14:30:00 GMT" />

                    <el-form label-width="120px" class="options-form">
                        <el-form-item label="转换模式">
                            <el-radio-group v-model="mode">
                                <el-radio-button label="timestampToDate">时间戳 → 日期</el-radio-button>
                                <el-radio-button label="dateToTimestamp">日期 → 时间戳</el-radio-button>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="日期格式" v-if="mode === 'timestampToDate'">
                            <el-select v-model="dateFormat">
                                <el-option v-for="fmt in dateFormats" :key="fmt.value" :label="fmt.label"
                                    :value="fmt.value" />
                            </el-select>
                            <el-input v-if="dateFormat === 'custom'" v-model="customDateFormat"
                                placeholder="如：YYYY/MM/DD HH:mm:ss" style="margin-top: 8px;" />
                        </el-form-item>

                        <el-form-item label="输入日期格式" v-else>
                            <el-select v-model="parseFormat">
                                <el-option v-for="fmt in parseFormats" :key="fmt.value" :label="fmt.label"
                                    :value="fmt.value" />
                            </el-select>
                            <el-input v-if="parseFormat === 'custom'" v-model="customParseFormatValue"
                                placeholder="如：YYYY/MM/DD HH:mm:ss" style="margin-top: 8px;" />
                        </el-form-item>

                        <el-form-item label="时区偏移">
                            <el-select v-model="timezone">
                                <el-option v-for="zone in timezones" :key="zone.value" :label="zone.label"
                                    :value="zone.value" />
                            </el-select>
                        </el-form-item>
                    </el-form>

                    <el-button type="primary" @click="convert" style="width: 100%;">开始转换</el-button>
                </el-card>
            </el-col>

            <el-col :span="12">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>结果</span>
                            <div class="actions">
                                <el-button text size="small" @click="copyResults"
                                    :disabled="!results.length">复制</el-button>
                                <el-button text size="small" @click="clearResults"
                                    :disabled="!results.length">清空</el-button>
                            </div>
                        </div>
                    </template>

                    <div v-if="results.length" class="result-table">
                        <el-table :data="results" border stripe height="420">
                            <el-table-column prop="input" label="原始值" width="220" />
                            <el-table-column prop="output" label="转换结果" />
                            <el-table-column prop="remark" label="备注" width="100" />
                        </el-table>
                    </div>
                    <el-empty v-else description="结果将在此展示" />
                </el-card>
            </el-col>
        </el-row>

        <el-card class="info-card">
            <template #header>
                <div class="card-header">
                    <span>使用说明</span>
                </div>
            </template>
            <ul class="info-list">
                <li>每行一条记录，可混合输入秒、毫秒时间戳或日期字符串。</li>
                <li>支持自定义日期格式与时区偏移，默认使用本地时区。</li>
            </ul>
        </el-card>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import utc from 'dayjs/plugin/utc'

dayjs.extend(customParseFormat)
dayjs.extend(utc)

const input = ref('')
const mode = ref('timestampToDate')
const dateFormat = ref('YYYY-MM-DD HH:mm:ss')
const customDateFormat = ref('')
const parseFormat = ref('YYYY-MM-DD HH:mm:ss')
const customParseFormatValue = ref('')
const timezone = ref(0)
const results = ref([])

const dateFormats = [
    { label: 'YYYY-MM-DD HH:mm:ss', value: 'YYYY-MM-DD HH:mm:ss' },
    { label: 'YYYY/MM/DD HH:mm', value: 'YYYY/MM/DD HH:mm' },
    { label: 'ISO 8601', value: 'YYYY-MM-DDTHH:mm:ss[Z]' },
    { label: 'RFC 2822', value: 'ddd, DD MMM YYYY HH:mm:ss ZZ' },
    { label: '自定义格式', value: 'custom' }
]

const parseFormats = [
    { label: 'YYYY-MM-DD HH:mm:ss', value: 'YYYY-MM-DD HH:mm:ss' },
    { label: 'YYYY/MM/DD HH:mm', value: 'YYYY/MM/DD HH:mm' },
    { label: 'ISO 8601', value: 'YYYY-MM-DDTHH:mm:ss' },
    { label: 'RFC 2822', value: 'ddd, DD MMM YYYY HH:mm:ss ZZ' },
    { label: '自定义格式', value: 'custom' }
]

const timezones = Array.from({ length: 27 }, (_, i) => {
    const offset = i - 12
    const label = `GMT ${offset >= 0 ? '+' : ''}${offset}:00`
    return {
        label,
        value: offset
    }
})

const getFormat = (type) => {
    if (type === 'output') {
        return dateFormat.value === 'custom' ? customDateFormat.value : dateFormat.value
    }
    return parseFormat.value === 'custom' ? customParseFormatValue.value : parseFormat.value
}

const clearInput = () => {
    input.value = ''
    results.value = []
}

const clearResults = () => {
    results.value = []
}

const paste = async () => {
    try {
        const text = await navigator.clipboard.readText()
        input.value = text
    } catch {
        ElMessage.warning('无法读取剪贴板，请手动粘贴')
    }
}

const convert = () => {
    if (!input.value.trim()) {
        ElMessage.warning('请输入需要转换的内容')
        return
    }

    const lines = input.value.split(/\n+/).map(line => line.trim()).filter(Boolean)
    const outputFormat = getFormat('output')
    const parseFmt = getFormat('parse')

    if (mode.value === 'timestampToDate' && !outputFormat) {
        ElMessage.warning('请设置输出格式')
        return
    }
    if (mode.value === 'dateToTimestamp' && !parseFmt) {
        ElMessage.warning('请设置输入日期格式')
        return
    }

    const tzMinutes = timezone.value * 60
    results.value = lines.map(line => {
        if (mode.value === 'timestampToDate') {
            return convertStamp(line, outputFormat, tzMinutes)
        }
        return convertDate(line, parseFmt, tzMinutes)
    })
}

const convertStamp = (value, format, tzMinutes) => {
    const num = Number(value)
    if (Number.isNaN(num)) {
        return { input: value, output: '无效时间戳', remark: '失败' }
    }

    const isMs = Math.abs(num) > 1e11
    const timestamp = isMs ? num : num * 1000
    const date = dayjs(timestamp).utcOffset(tzMinutes)
    if (!date.isValid()) {
        return { input: value, output: '解析失败', remark: '失败' }
    }

    return {
        input: value,
        output: date.format(format),
        remark: isMs ? '毫秒' : '秒'
    }
}

const convertDate = (value, format, tzMinutes) => {
    const parsed = dayjs(value, format, true)
    if (!parsed.isValid()) {
        return { input: value, output: '解析失败', remark: '失败' }
    }

    const adjusted = parsed.utcOffset(tzMinutes)
    return {
        input: value,
        output: `${adjusted.unix()}（秒） / ${adjusted.valueOf()}（毫秒）`,
        remark: '成功'
    }
}

const copyResults = async () => {
    if (!results.value.length) return
    const text = results.value.map(item => `${item.input} => ${item.output}`).join('\n')
    try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('结果已复制')
    } catch {
        ElMessage.error('复制失败')
    }
}
</script>

<style scoped>
.timestamp-tool {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.tool-header {
    text-align: center;
    margin-bottom: 30px;
}

.tool-header h1 {
    font-size: 2.2rem;
    margin-bottom: 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
}

.actions {
    display: flex;
    gap: 10px;
}

.options-form {
    margin: 20px 0;
}

.result-table {
    margin-top: 10px;
}

.info-card {
    margin-top: 30px;
}

.info-list {
    margin: 0;
    padding-left: 20px;
    color: #666;
    line-height: 1.8;
}
</style>
